import { useState, useEffect } from "react";
import { BottomNavigation } from "@/components/ui/bottom-navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  Share,
  Wand2,
  Copy,
  Download,
  Heart,
  MessageCircle,
  RefreshCw,
  Sparkles,
  Grid3X3,
  Edit3,
} from "lucide-react";

interface Platform {
  id: string;
  name: string;
  icon: string;
  maxPhotos: number;
  layout: "grid" | "sequence";
  color: string;
}

const platforms: Platform[] = [
  {
    id: "xiaohongshu",
    name: "小红书",
    icon: "��",
    maxPhotos: 13,
    layout: "sequence",
    color: "bg-red-100 text-red-800",
  },
  {
    id: "wechat",
    name: "朋友圈",
    icon: "💬",
    maxPhotos: 9,
    layout: "grid",
    color: "bg-green-100 text-green-800",
  },
  {
    id: "weibo",
    name: "微博",
    icon: "🐦",
    maxPhotos: 9,
    layout: "grid",
    color: "bg-orange-100 text-orange-800",
  },
];

// Auto-generated content templates
const generateContent = (platform: Platform, data: any) => {
  const isFromTimeline = data?.source === "timeline";
  const isFromLocation = data?.source === "location";

  const basePhotos = [
    "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
    "https://images.pexels.com/photos/5504722/pexels-photo-5504722.jpeg",
    "https://images.pexels.com/photos/4241550/pexels-photo-4241550.jpeg",
    "https://images.pexels.com/photos/2614816/pexels-photo-2614816.jpeg",
    "https://images.pexels.com/photos/30629862/pexels-photo-30629862.jpeg",
    "https://images.pexels.com/photos/5220043/pexels-photo-5220043.jpeg",
    "https://images.pexels.com/photos/10967785/pexels-photo-10967785.jpeg",
    "https://images.pexels.com/photos/2181230/pexels-photo-2181230.jpeg",
    "https://images.pexels.com/photos/3222196/pexels-photo-3222196.jpeg",
    "https://images.pexels.com/photos/7993600/pexels-photo-7993600.jpeg",
  ];

  const selectedPhotos = basePhotos.slice(0, platform.maxPhotos);

  if (platform.id === "xiaohongshu") {
    return {
      title: isFromTimeline
        ? `${data.title} | 完美旅行记录📸`
        : `${data.title} | 超棒的体验✨`,
      content: isFromTimeline
        ? `这个月的旅行真的太精彩了！每一张照片都记录着美好的回忆💕\n\n从早晨的第一缕阳光到夜晚的星空，每个瞬间都值得珍藏✨\n\n#旅行日记 #美好回忆 #摄影分享 #生活记录`
        : `今天探索了这个超棒的地方！氛围感满满，拍出来的照片都太美了📸\n\n每个角落都有惊喜，强烈推荐大家也来打卡！\n\n#探店 #拍照圣地 #美好生活 #推荐`,
      photos: selectedPhotos,
      tags: isFromTimeline
        ? ["#旅行日记", "#美好回忆", "#摄影分享", "#生活记录"]
        : ["#探店", "#拍照圣地", "#美好生活", "#推荐"],
    };
  } else if (platform.id === "wechat") {
    return {
      title: data.title,
      content: isFromTimeline
        ? `美好的时光总是过得很快，这次的旅行留下了太多难忘的回忆。每一张照片都是最珍贵的纪念。`
        : `今天去了一个特别棒的地方，感受到了不一样的美好。和朋友们分享这份快乐！`,
      photos: selectedPhotos,
      tags: [],
    };
  } else {
    // weibo
    return {
      title: `${data.title} - 分享生活的美好瞬间`,
      content: isFromTimeline
        ? `这段旅程真的太棒了！每个瞬间都值得记录和分享 🌟 生活就是要这样精彩！`
        : `发现了一个超棒的地方！氛围感爆棚，必须和大家分享一下 📸✨`,
      photos: selectedPhotos,
      tags: isFromTimeline
        ? ["#旅行", "#摄影", "#生活", "#美好"]
        : ["#探店", "#分享", "#生活", "#美好"],
    };
  }
};

const smartSuggestions = [
  {
    id: 1,
    title: "故宫秋日游记",
    platform: "小红书",
    photos: Array(9).fill(
      "https://images.pexels.com/photos/9373300/pexels-photo-9373300.jpeg",
    ),
    caption:
      "秋日故宫，金桂飘香🍂 走进这座承载着六百年历史的紫禁城，感受古韵与现代的完美融合✨",
    tags: ["#故宫", "#秋天", "#北京旅行", "#古建筑"],
    engagement: { likes: 128, comments: 23 },
    status: "ready",
  },
];

// Separate PostCard component to avoid hooks in map
function PostCard({
  suggestion,
  platforms,
  renderPhotoLayout,
}: {
  suggestion: any;
  platforms: Platform[];
  renderPhotoLayout: (photos: string[], platform?: Platform) => JSX.Element;
}) {
  const [postPlatform, setPostPlatform] = useState<Platform>(
    platforms.find((p) => p.name === suggestion.platform) || platforms[0],
  );

  // Editing states
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [isEditingContent, setIsEditingContent] = useState(false);
  const [editedTitle, setEditedTitle] = useState(suggestion.title);
  const [editedContent, setEditedContent] = useState(suggestion.caption);
  const [editedPhotos, setEditedPhotos] = useState([...suggestion.photos]);
  const [draggedIndex, setDraggedIndex] = useState<number | null>(null);

  const regenerateTitle = () => {
    setEditedTitle("AI重新生成的标题：" + Date.now());
  };

  const regeneratePhotos = () => {
    const newPhotos = [...editedPhotos].sort(() => Math.random() - 0.5);
    setEditedPhotos(newPhotos);
  };

  const regenerateContent = () => {
    setEditedContent("AI重新生成的内容：这是全新的内容描述..." + Date.now());
  };

  const handleTitleSave = () => {
    setIsEditingTitle(false);
  };

  const handleContentSave = () => {
    setIsEditingContent(false);
  };

  const handleDragStart = (e: React.DragEvent, index: number) => {
    setDraggedIndex(index);
    e.dataTransfer.effectAllowed = "move";
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
  };

  const handleDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();

    if (draggedIndex === null) return;

    const newPhotos = [...editedPhotos];
    const draggedPhoto = newPhotos[draggedIndex];

    // Remove dragged item
    newPhotos.splice(draggedIndex, 1);
    // Insert at new position
    newPhotos.splice(dropIndex, 0, draggedPhoto);

    setEditedPhotos(newPhotos);
    setDraggedIndex(null);
  };

  const renderDragDropPhotoLayout = (photos: string[], platform: Platform) => {
    const limitedPhotos = photos.slice(0, platform.maxPhotos);

    if (platform.layout === "grid") {
      return (
        <div className="grid grid-cols-3 gap-2">
          {limitedPhotos.map((photo, index) => (
            <div
              key={index}
              className="aspect-square rounded overflow-hidden cursor-move relative group"
              draggable
              onDragStart={(e) => handleDragStart(e, index)}
              onDragOver={handleDragOver}
              onDrop={(e) => handleDrop(e, index)}
            >
              <img
                src={photo}
                alt={`Photo ${index + 1}`}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <span className="text-white text-xs">拖动排序</span>
              </div>
            </div>
          ))}
        </div>
      );
    } else {
      return (
        <div className="flex gap-2 overflow-x-auto pb-2">
          {limitedPhotos.map((photo, index) => (
            <div
              key={index}
              className="w-32 h-32 flex-shrink-0 rounded overflow-hidden cursor-move relative group"
              draggable
              onDragStart={(e) => handleDragStart(e, index)}
              onDragOver={handleDragOver}
              onDrop={(e) => handleDrop(e, index)}
            >
              <img
                src={photo}
                alt={`Photo ${index + 1}`}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <span className="text-white text-xs">拖��</span>
              </div>
            </div>
          ))}
        </div>
      );
    }
  };

  return (
    <Card className="overflow-hidden">
      <CardContent className="p-0">
        {/* Platform Switcher at Top */}
        <div className="p-4 border-b border-border">
          <div className="flex gap-2 overflow-x-auto">
            {platforms.map((platform) => (
              <Button
                key={platform.id}
                variant={
                  postPlatform.id === platform.id ? "default" : "outline"
                }
                size="sm"
                onClick={() => setPostPlatform(platform)}
                className="flex-shrink-0"
              >
                <span className="mr-1">{platform.icon}</span>
                {platform.name}
              </Button>
            ))}
          </div>
        </div>

        {/* Title Section */}
        <div className="bg-blue-50 p-3 border-b border-border">
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <div className="text-xs text-muted-foreground mb-1">标题</div>
              {isEditingTitle ? (
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={editedTitle}
                    onChange={(e) => setEditedTitle(e.target.value)}
                    className="flex-1 font-semibold text-foreground bg-transparent border-b border-primary focus:outline-none"
                    onKeyDown={(e) => {
                      if (e.key === "Enter") handleTitleSave();
                      if (e.key === "Escape") {
                        setEditedTitle(suggestion.title);
                        setIsEditingTitle(false);
                      }
                    }}
                    autoFocus
                  />
                  <Button variant="ghost" size="sm" onClick={handleTitleSave}>
                    <span className="text-green-600">✓</span>
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setEditedTitle(suggestion.title);
                      setIsEditingTitle(false);
                    }}
                  >
                    <span className="text-red-600">✗</span>
                  </Button>
                </div>
              ) : (
                <h3
                  className="font-semibold text-foreground cursor-pointer hover:bg-blue-100 p-1 rounded"
                  onClick={() => setIsEditingTitle(true)}
                >
                  {editedTitle}
                </h3>
              )}
            </div>
            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsEditingTitle(true)}
              >
                <Edit3 className="h-3 w-3" />
              </Button>
              <Button variant="ghost" size="sm" onClick={regenerateTitle}>
                <Wand2 className="h-4 w-4 mr-1" />
                重新生成
              </Button>
            </div>
          </div>
        </div>

        {/* Photos Section */}
        <div className="bg-green-50 p-3 border-b border-border">
          <div className="flex items-center justify-between mb-3">
            <div className="text-xs text-muted-foreground">图片 (拖动排序)</div>
            <Button variant="ghost" size="sm" onClick={regeneratePhotos}>
              <Wand2 className="h-4 w-4 mr-1" />
              重新生成
            </Button>
          </div>
          {renderDragDropPhotoLayout(editedPhotos, postPlatform)}
        </div>

        {/* Content Section */}
        <div className="bg-yellow-50 p-3 border-b border-border">
          <div className="flex items-center justify-between mb-3">
            <div className="text-xs text-muted-foreground">正文</div>
            <div className="flex items-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsEditingContent(true)}
              >
                <Edit3 className="h-3 w-3" />
              </Button>
              <Button variant="ghost" size="sm" onClick={regenerateContent}>
                <Wand2 className="h-4 w-4 mr-1" />
                重新生成
              </Button>
            </div>
          </div>
          {isEditingContent ? (
            <div className="mb-3">
              <textarea
                value={editedContent}
                onChange={(e) => setEditedContent(e.target.value)}
                className="w-full min-h-[80px] p-2 text-foreground leading-relaxed bg-white border border-gray-300 rounded focus:outline-none focus:border-primary resize-vertical"
                onKeyDown={(e) => {
                  if (e.key === "Escape") {
                    setEditedContent(suggestion.caption);
                    setIsEditingContent(false);
                  }
                }}
                autoFocus
              />
              <div className="flex items-center gap-2 mt-2">
                <Button variant="ghost" size="sm" onClick={handleContentSave}>
                  <span className="text-green-600 mr-1">✓</span>
                  保存
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => {
                    setEditedContent(suggestion.caption);
                    setIsEditingContent(false);
                  }}
                >
                  <span className="text-red-600 mr-1">✗</span>
                  取消
                </Button>
              </div>
            </div>
          ) : (
            <p
              className="text-foreground leading-relaxed mb-3 cursor-pointer hover:bg-yellow-100 p-1 rounded"
              onClick={() => setIsEditingContent(true)}
            >
              {editedContent}
            </p>
          )}
          <div className="flex flex-wrap gap-1">
            {suggestion.tags.map((tag: string, index: number) => (
              <Badge key={index} variant="outline" className="text-xs">
                {tag}
              </Badge>
            ))}
          </div>
        </div>

        {/* Actions */}
        <div className="p-4 bg-muted/20">
          <div className="flex gap-2">
            <Button size="sm" className="flex-1">
              <Share className="h-4 w-4 mr-2" />
              立即发布
            </Button>
            <Button variant="outline" size="sm">
              <Copy className="h-4 w-4" />
            </Button>
            <Button variant="outline" size="sm">
              <Download className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

export default function SocialMedia() {
  const [selectedPlatform, setSelectedPlatform] = useState<Platform>(
    platforms[0],
  );
  const [posts, setPosts] = useState(smartSuggestions);
  const [currentContent, setCurrentContent] = useState<any>(null);
  const [isEditing, setIsEditing] = useState(false);

  // Editing states for auto-generated content
  const [isEditingAutoTitle, setIsEditingAutoTitle] = useState(false);
  const [isEditingAutoContent, setIsEditingAutoContent] = useState(false);
  const [editedAutoTitle, setEditedAutoTitle] = useState("");
  const [editedAutoContent, setEditedAutoContent] = useState("");
  const [editedAutoPhotos, setEditedAutoPhotos] = useState<string[]>([]);
  const [autoDraggedIndex, setAutoDraggedIndex] = useState<number | null>(null);

  // Check for new auto-generated content
  useEffect(() => {
    const latestPost = localStorage.getItem("latestSocialPost");
    if (latestPost) {
      const postData = JSON.parse(latestPost);
      const autoContent = generateContent(selectedPlatform, postData);

      const newPost = {
        id: postData.id,
        title: autoContent.title,
        platform: selectedPlatform.name,
        photos: autoContent.photos,
        caption: autoContent.content,
        tags: autoContent.tags,
        engagement: { likes: 0, comments: 0 },
        status: "draft",
        isAutoGenerated: true,
        sourceData: postData,
      };

      setPosts((prev) => [newPost, ...prev]);
      setCurrentContent(newPost);
      setEditedAutoTitle(newPost.title);
      setEditedAutoContent(newPost.caption);
      setEditedAutoPhotos(newPost.photos);
      localStorage.removeItem("latestSocialPost");
    }
  }, []);

  // Update content when platform changes
  useEffect(() => {
    if (currentContent?.isAutoGenerated && currentContent?.sourceData) {
      const updatedContent = generateContent(
        selectedPlatform,
        currentContent.sourceData,
      );
      setCurrentContent((prev) => ({
        ...prev,
        title: updatedContent.title,
        caption: updatedContent.content,
        photos: updatedContent.photos,
        tags: updatedContent.tags,
        platform: selectedPlatform.name,
      }));
      setEditedAutoTitle(updatedContent.title);
      setEditedAutoContent(updatedContent.content);
      setEditedAutoPhotos(updatedContent.photos);
    }
  }, [selectedPlatform]);

  const refreshContent = () => {
    if (currentContent?.sourceData) {
      const refreshedContent = generateContent(
        selectedPlatform,
        currentContent.sourceData,
      );
      setCurrentContent((prev) => ({
        ...prev,
        title: refreshedContent.title,
        caption: refreshedContent.content,
        photos: refreshedContent.photos,
        tags: refreshedContent.tags,
      }));
      setEditedAutoTitle(refreshedContent.title);
      setEditedAutoContent(refreshedContent.content);
      setEditedAutoPhotos(refreshedContent.photos);
    }
  };

  const handleAutoTitleSave = () => {
    setIsEditingAutoTitle(false);
    if (currentContent) {
      setCurrentContent((prev) => ({ ...prev, title: editedAutoTitle }));
    }
  };

  const handleAutoContentSave = () => {
    setIsEditingAutoContent(false);
    if (currentContent) {
      setCurrentContent((prev) => ({ ...prev, caption: editedAutoContent }));
    }
  };

  const handleAutoDragStart = (e: React.DragEvent, index: number) => {
    setAutoDraggedIndex(index);
    e.dataTransfer.effectAllowed = "move";
  };

  const handleAutoDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
  };

  const handleAutoDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault();

    if (autoDraggedIndex === null) return;

    const newPhotos = [...editedAutoPhotos];
    const draggedPhoto = newPhotos[autoDraggedIndex];

    newPhotos.splice(autoDraggedIndex, 1);
    newPhotos.splice(dropIndex, 0, draggedPhoto);

    setEditedAutoPhotos(newPhotos);
    if (currentContent) {
      setCurrentContent((prev) => ({ ...prev, photos: newPhotos }));
    }
    setAutoDraggedIndex(null);
  };

  const renderAutoDragDropPhotoLayout = (photos: string[]) => {
    const limitedPhotos = photos.slice(0, selectedPlatform.maxPhotos);

    if (selectedPlatform.layout === "grid") {
      return (
        <div className="grid grid-cols-3 gap-2">
          {limitedPhotos.map((photo, index) => (
            <div
              key={index}
              className="aspect-square rounded overflow-hidden cursor-move relative group"
              draggable
              onDragStart={(e) => handleAutoDragStart(e, index)}
              onDragOver={handleAutoDragOver}
              onDrop={(e) => handleAutoDrop(e, index)}
            >
              <img
                src={photo}
                alt={`Photo ${index + 1}`}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <span className="text-white text-xs">拖动排序</span>
              </div>
            </div>
          ))}
        </div>
      );
    } else {
      return (
        <div className="flex gap-2 overflow-x-auto pb-2">
          {limitedPhotos.map((photo, index) => (
            <div
              key={index}
              className="w-32 h-32 flex-shrink-0 rounded overflow-hidden cursor-move relative group"
              draggable
              onDragStart={(e) => handleAutoDragStart(e, index)}
              onDragOver={handleAutoDragOver}
              onDrop={(e) => handleAutoDrop(e, index)}
            >
              <img
                src={photo}
                alt={`Photo ${index + 1}`}
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <span className="text-white text-xs">拖动</span>
              </div>
            </div>
          ))}
        </div>
      );
    }
  };

  const renderPhotoLayout = (
    photos: string[],
    platform: Platform = selectedPlatform,
  ) => {
    if (platform.layout === "grid") {
      return (
        <div className="grid grid-cols-3 gap-2">
          {photos.map((photo, index) => (
            <div key={index} className="aspect-square rounded overflow-hidden">
              <img
                src={photo}
                alt={`Photo ${index + 1}`}
                className="w-full h-full object-cover"
              />
            </div>
          ))}
        </div>
      );
    } else {
      return (
        <div className="flex gap-2 overflow-x-auto pb-2">
          {photos.map((photo, index) => (
            <div
              key={index}
              className="w-32 h-32 flex-shrink-0 rounded overflow-hidden"
            >
              <img
                src={photo}
                alt={`Photo ${index + 1}`}
                className="w-full h-full object-cover"
              />
            </div>
          ))}
        </div>
      );
    }
  };

  return (
    <div className="min-h-screen bg-background pb-20">
      {/* Header */}
      <header className="sticky top-0 z-40 bg-background/80 backdrop-blur-lg border-b border-border">
        <div className="flex items-center justify-between p-4">
          <div>
            <h1 className="text-2xl font-bold text-foreground">社媒</h1>
            <p className="text-sm text-muted-foreground">
              智能生成社交媒体内容
            </p>
          </div>
          <Button variant="outline" size="sm">
            <Wand2 className="h-4 w-4 mr-2" />
            生成新内容
          </Button>
        </div>
      </header>

      {/* Current Auto-Generated Content */}
      {currentContent && (
        <div className="p-4 border-b border-border bg-gradient-to-r from-blue-50 to-purple-50">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-purple-600" />
              <h3 className="font-semibold text-foreground">AI 生成内容</h3>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="ghost" size="sm" onClick={refreshContent}>
                <Wand2 className="h-4 w-4 mr-1" />
                重新生成
              </Button>
              <Button variant="ghost" size="sm">
                <Edit3 className="h-4 w-4 mr-1" />
                编辑
              </Button>
            </div>
          </div>

          <Card className="mb-4">
            <CardContent className="p-0">
              {/* Platform Switcher at Top */}
              <div className="p-4 border-b border-border">
                <div className="flex gap-2 overflow-x-auto">
                  {platforms.map((platform) => (
                    <Button
                      key={platform.id}
                      variant={
                        selectedPlatform.id === platform.id
                          ? "default"
                          : "outline"
                      }
                      size="sm"
                      onClick={() => setSelectedPlatform(platform)}
                      className="flex-shrink-0"
                    >
                      <span className="mr-1">{platform.icon}</span>
                      {platform.name}
                    </Button>
                  ))}
                </div>
              </div>

              {/* Title Section */}
              <div className="bg-blue-50 p-3 border-b border-border">
                <div className="flex items-center justify-between">
                  <div className="flex-1">
                    <div className="text-xs text-muted-foreground mb-1">
                      标题
                    </div>
                    {isEditingAutoTitle ? (
                      <div className="flex items-center gap-2">
                        <input
                          type="text"
                          value={editedAutoTitle}
                          onChange={(e) => setEditedAutoTitle(e.target.value)}
                          className="flex-1 font-semibold text-foreground bg-transparent border-b border-primary focus:outline-none"
                          onKeyDown={(e) => {
                            if (e.key === "Enter") handleAutoTitleSave();
                            if (e.key === "Escape") {
                              setEditedAutoTitle(currentContent.title);
                              setIsEditingAutoTitle(false);
                            }
                          }}
                          autoFocus
                        />
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={handleAutoTitleSave}
                        >
                          <span className="text-green-600">✓</span>
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setEditedAutoTitle(currentContent.title);
                            setIsEditingAutoTitle(false);
                          }}
                        >
                          <span className="text-red-600">✗</span>
                        </Button>
                      </div>
                    ) : (
                      <h4
                        className="font-semibold text-foreground cursor-pointer hover:bg-blue-100 p-1 rounded"
                        onClick={() => setIsEditingAutoTitle(true)}
                      >
                        {editedAutoTitle}
                      </h4>
                    )}
                  </div>
                  <div className="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setIsEditingAutoTitle(true)}
                    >
                      <Edit3 className="h-3 w-3" />
                    </Button>
                    <Button variant="ghost" size="sm" onClick={refreshContent}>
                      <Wand2 className="h-4 w-4 mr-1" />
                      重新生成
                    </Button>
                  </div>
                </div>
              </div>

              {/* Photos Section */}
              <div className="bg-green-50 p-3 border-b border-border">
                <div className="flex items-center justify-between mb-3">
                  <div className="text-xs text-muted-foreground">
                    图片 (拖动排序)
                  </div>
                  <Button variant="ghost" size="sm" onClick={refreshContent}>
                    <Wand2 className="h-4 w-4 mr-1" />
                    重新生成
                  </Button>
                </div>
                {renderAutoDragDropPhotoLayout(editedAutoPhotos)}
              </div>

              {/* Content Section */}
              <div className="bg-yellow-50 p-3 border-b border-border">
                <div className="flex items-center justify-between mb-3">
                  <div className="text-xs text-muted-foreground">正文</div>
                  <div className="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setIsEditingAutoContent(true)}
                    >
                      <Edit3 className="h-3 w-3" />
                    </Button>
                    <Button variant="ghost" size="sm" onClick={refreshContent}>
                      <Wand2 className="h-4 w-4 mr-1" />
                      重新生成
                    </Button>
                  </div>
                </div>
                {isEditingAutoContent ? (
                  <div className="mb-3">
                    <textarea
                      value={editedAutoContent}
                      onChange={(e) => setEditedAutoContent(e.target.value)}
                      className="w-full min-h-[80px] p-2 text-foreground leading-relaxed bg-white border border-gray-300 rounded focus:outline-none focus:border-primary resize-vertical"
                      onKeyDown={(e) => {
                        if (e.key === "Escape") {
                          setEditedAutoContent(currentContent.caption);
                          setIsEditingAutoContent(false);
                        }
                      }}
                      autoFocus
                    />
                    <div className="flex items-center gap-2 mt-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={handleAutoContentSave}
                      >
                        <span className="text-green-600 mr-1">✓</span>
                        保存
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setEditedAutoContent(currentContent.caption);
                          setIsEditingAutoContent(false);
                        }}
                      >
                        <span className="text-red-600 mr-1">✗</span>
                        取消
                      </Button>
                    </div>
                  </div>
                ) : (
                  <p
                    className="text-foreground leading-relaxed whitespace-pre-line mb-3 cursor-pointer hover:bg-yellow-100 p-1 rounded"
                    onClick={() => setIsEditingAutoContent(true)}
                  >
                    {editedAutoContent}
                  </p>
                )}
                {currentContent.tags && currentContent.tags.length > 0 && (
                  <div className="flex flex-wrap gap-1">
                    {currentContent.tags.map((tag: string, index: number) => (
                      <Badge key={index} variant="outline" className="text-xs">
                        {tag}
                      </Badge>
                    ))}
                  </div>
                )}
              </div>

              {/* Actions */}
              <div className="p-4 bg-muted/20">
                <div className="flex gap-2">
                  <Button size="sm" className="flex-1">
                    <Share className="h-4 w-4 mr-2" />
                    立即发布
                  </Button>
                  <Button variant="outline" size="sm">
                    <Copy className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm">
                    <Download className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Existing Posts */}
      <div className="p-4">
        <h2 className="text-lg font-semibold text-foreground mb-4">历史内容</h2>
        <div className="space-y-4">
          {posts.map((suggestion) => (
            <PostCard
              key={suggestion.id}
              suggestion={suggestion}
              platforms={platforms}
              renderPhotoLayout={renderPhotoLayout}
            />
          ))}
        </div>

        {/* Create New */}
        <Card className="border-dashed border-2 border-muted-foreground/20 mt-4">
          <CardContent className="p-8 text-center">
            <Wand2 className="h-8 w-8 text-muted-foreground mx-auto mb-3" />
            <h3 className="font-medium text-foreground mb-2">创建新内容</h3>
            <p className="text-sm text-muted-foreground mb-4">
              选择照片，AI 将为您生成精美的社交媒体内容
            </p>
            <Button>开始创建</Button>
          </CardContent>
        </Card>
      </div>

      <BottomNavigation />
    </div>
  );
}
